package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dto.EmpDto;
import com.itheima.dto.EmpLoginDto;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.MyResponseResult;
import com.itheima.pojo.PageBean;
import com.itheima.service.EmpService;
import com.itheima.utils.MyJwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private MyJwtUtils myJwtUtils;

    @Override
    public PageBean<Emp> getByPage(Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        Page<Emp> emps = (Page<Emp>)empMapper.getEByPage();
        return new PageBean<Emp>(emps.getTotal(),emps.getResult());
    }

    @Override
    public PageBean<Emp> getByPage(Integer page, Integer pageSize, EmpDto empDto) {

        PageHelper.startPage(page, pageSize);
        Page<Emp> emps = (Page<Emp>)empMapper.getByPage(empDto);
//        PageInfo<Emp> info = PageInfo.of(emps);
        return new PageBean<Emp>(emps.getTotal(),emps.getResult());
    }

    @Override
    public int delByIds(Integer[] ids) {

        return empMapper.delByIds(ids);
    }

    @Override
    public int insertEmp(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        return empMapper.insertEmp(emp);
    }

    @Override
    public Emp getById(Integer id) {
        return empMapper.getById(id);
    }

    @Override
    public MyResponseResult<String> login(EmpLoginDto dto) {
        Emp emp = empMapper.findByUsernameAndPassword(dto);
        if(emp == null){
            return MyResponseResult.error("NOT_LOGIN");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("id",emp.getId());
        map.put("name",emp.getName());
        String jwt = myJwtUtils.createJwt(map);
        return MyResponseResult.ok(jwt);



    }

    @Override
    public int delByDeptId(Integer deptId) {
        return empMapper.delByDeptId(deptId);
    }



    /*@Override
    public PageBean<Emp> getByPage(Integer pageNum, Integer pageSize) {

        Integer start = (pageNum - 1) * pageSize;
        List<Emp> emps = empMapper.getByPage(start, pageSize);
        Long total = empMapper.getTotal();
        return new PageBean<>(total,emps);

    }*/


}
